import { AES, enc } from 'crypto-js';

// 密钥
const SECRET = 'yangAdmin';
/**
 * setLocal 设置数据缓存到浏览器中
 * @param key 保存key值
 * @param data 保存数据
 * @param isEncrypt 是否需要加密 默认false
 */
export function setLocal(key:string, data:any, isEncrypt = true){
  if(key && data){
    const ciphertext = isEncrypt ?  AES.encrypt(data, SECRET).toString() : data;
    window.localStorage.setItem(key, ciphertext);
  }else {
    console.error(`设置${key}失败`);
  }
}
/**
 * getLocal 获取浏览器中缓存字段
 * @param key 获取当前key值
 * @param isEncrypt 是否为加密数据
 */
export function getLocal<T>(key:string, isEncrypt=true) {
  const value = window.localStorage.getItem(key) || '';
  if(isEncrypt){
    const bytes = AES.decrypt(value, SECRET);
    return bytes.toString(enc.Utf8) as T;
  }else return value as T;
}


export function removeLocal(key:string){
  if(key){
    window.localStorage.removeItem(key);
  }else {
    console.error(`删除${key}失败`);
  }
}

